package com.nisco.dms.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.nisco.dms.entity.CoreEntity;
import com.nisco.dms.entity.Menu;
import com.nisco.dms.entity.RolePermission;
import com.nisco.dms.entity.User;
import com.nisco.dms.entity.UserRole;
import com.nisco.dms.service.MenuService;
import com.nisco.dms.service.UserRoleService;
import com.nisco.dms.service.UserService;
import com.nisco.dms.shiro.ShiroDbRealm;
import com.nisco.dms.util.ControllerUtil;
import com.nisco.dms.util.dwz.AjaxObject;
import com.nisco.dms.util.pub.StringConstants;
/**
 * 
 * @author joey
 *
 */
@Controller
@RequestMapping(value = "/menu")
public class MenuController {
	// @Autowired
	// private MenuService menuService;
	//
	// @RequestMapping(value = "")
	// public String list(Model model, ServletRequest request) {
	// Long userId = getCurrentUserId();
	// List<Menu> menus = menuService.getMenuByUserId(userId);
	// model.addAttribute("menus", menus);
	// return "menu/main";
	// }
	//
	// /**
	// * 取出Shiro中的当前用户Id.
	// */
	// private Long getCurrentUserId() {
	// ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
	// return user.id;
	// }

	@Autowired
	private UserService userService;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private MenuService moduleService;

	private static final String INDEX = "menu/menuList";
	private static final String UPDATE_PASSWORD = "menu/updatePwd";
	private static final String UPDATE_BASE = "menu/updateBase";

	@RequiresAuthentication
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String index(HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject.getPrincipal();

		// User user = userService.get(shiroUser.getLoginName());
		List<UserRole> userRoles = userRoleService.find(shiroUser.getId());
		shiroUser.getUser().setUserRoles(userRoles);
		//初始化核心实体类shiroUser
		CoreEntity.shiroUser = shiroUser;
		//初始化控制层工具类shiroUser
		ControllerUtil.shiroUser = shiroUser;
		
		Menu menuModule = getMenuModule(userRoles);
		
		// 这个是放入user还是shiroUser呢？
		request.getSession().setAttribute(StringConstants.LOGIN_USER, shiroUser.getUser());
		request.setAttribute("menuModule", menuModule);
		return INDEX;
	}

	private Menu getMenuModule(List<UserRole> userRoles) {
		// 得到所有权限
		Set<String> permissionSet = Sets.newHashSet();
		for (UserRole userRole : userRoles) {
			List<RolePermission> rplist=userRole.getRole().getPermissionList();
			Set<String> tmp =new HashSet<String>();
			for (RolePermission rolePermission : rplist)
			{
				tmp.add(rolePermission.getStrPermission());
			}
			permissionSet.addAll(tmp);
		}

		Menu rootModule = moduleService.getTree();
		List<Menu> list1 = Lists.newArrayList();
		for (Menu m1 : rootModule.getChildren()) {
			// 只加入拥有view权限的Module
			if (permissionSet.contains(m1.getStrSn() + ":" + StringConstants.OPERATION_VIEW)) {
				List<Menu> list2 = Lists.newArrayList();
				for (Menu m2 : m1.getChildren()) {
					if (permissionSet.contains(m2.getStrSn() + ":" + StringConstants.OPERATION_VIEW)) {
						list2.add(m2);
						List<Menu> list3 = Lists.newArrayList();
						for (Menu m3 : m2.getChildren()) 
						{
							if (permissionSet.contains(m3.getStrSn() + ":" + StringConstants.OPERATION_VIEW)) 
							list3.add(m3);
						}
						m2.setChildren(list3);
					}
					
				}
				
				m1.setChildren(list2);
				list1.add(m1);
			}
		}
		rootModule.setChildren(list1);

		return rootModule;
	}

	@RequestMapping(value="/switchEnv/{navMenuId}")
	public @ResponseBody String switchEnv(@PathVariable String  navMenuId,HttpServletRequest request,HttpServletResponse response)
	{
		System.out.println(navMenuId);
		Menu m=moduleService.findOne(navMenuId);
		Subject subject = SecurityUtils.getSubject();
		ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject.getPrincipal();
		List<UserRole> userRoles = userRoleService.find(shiroUser.getId());
		shiroUser.getUser().setUserRoles(userRoles);
		Menu menuModule = getNavMenuModule(userRoles,m);
		StringBuffer sb=new StringBuffer();
		List<Menu> mlist=new ArrayList<Menu>();
		mlist=menuModule.getChildren();
		if(mlist.size()>0)
		{
			sb.append("<div class='accordion' fillSpace='sideBar'>");
		for (Menu module : mlist) 
		{
			String temp="<div class='accordionHeader'><h2><span>Folder</span>"+module.getStrName()+"</h2></div>";
			sb.append(temp);
			List<Menu> mlist1=new ArrayList<Menu>();
			mlist1=module.getChildren();
			sb.append("<div class='accordionContent'><ul class='tree treeFolder'>");
			for (Menu module2 : mlist1) 
			{
				temp="<li><a href='"+module2.getProgram().getStrUrl()+"?moduleListNavId=moduleListNav_"+module2.getId()+"' target='navTab' rel='moduleListNav_"+module2.getId()+"'>"+module2.getStrName()+"</a></li>";
				sb.append(temp);
			}
			sb.append("</ul></div>");
		}
			sb.append("</div>");
		}
		AjaxObject ajaxObject = new AjaxObject(200,sb.toString(),"sidebar","","","closeCurrent");
		return ajaxObject.getMessage().toString();
	}
	private Menu getNavMenuModule(List<UserRole> userRoles,Menu module) {
		// 得到所有权限
		Set<String> permissionSet = Sets.newHashSet();
		for (UserRole userRole : userRoles) {
			List<RolePermission> rplist=userRole.getRole().getPermissionList();
			Set<String> tmp =new HashSet<String>();
			for (RolePermission rolePermission : rplist)
			{
				tmp.add(rolePermission.getStrPermission());
			}
			permissionSet.addAll(tmp);
		}
		Menu rootModule = moduleService.getTree();
		List<Menu> list1 = Lists.newArrayList();
		for (Menu m1 : module.getChildren()) {
			// 只加入拥有view权限的Module
			if (permissionSet.contains(m1.getStrSn() + ":" + StringConstants.OPERATION_VIEW)) {
				List<Menu> list2 = Lists.newArrayList();
				for (Menu m2 : m1.getChildren()) {
					if (permissionSet.contains(m2.getStrSn() + ":" + StringConstants.OPERATION_VIEW)) {
						list2.add(m2);
					}
					
				}
				
				m1.setChildren(list2);
				list1.add(m1);
			}
		}
		module.setChildren(list1);
		module.setParent(rootModule);
		return module;
	}
	@RequestMapping(value = "/updatePwd", method = RequestMethod.GET)
	public String updatePassword() {
		return UPDATE_PASSWORD;
	}

	@RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
	public @ResponseBody
	String updatePassword(HttpServletRequest request, String oldPassword, String plainPassword, String rPassword) {
		User user = (User) request.getSession().getAttribute(StringConstants.LOGIN_USER);

		if (plainPassword.equals(rPassword)) {
			user.setPlainPassword(plainPassword);
			userService.update(user);

			AjaxObject ajaxObject = new AjaxObject("密码修改成功！");
			return ajaxObject.toString();
		}

		AjaxObject ajaxObject = new AjaxObject("密码修改失败！");
		ajaxObject.setStatusCode(AjaxObject.STATUS_CODE_FAILURE);
		ajaxObject.setCallbackType("");
		return ajaxObject.toString();
	}

	@RequestMapping(value = "/updateBase", method = RequestMethod.GET)
	public String preUpdate(Map<String, Object> map) {
		map.put("user", ControllerUtil.currentUser());
		return UPDATE_BASE;
	}

	@RequestMapping(value = "/updateBase", method = RequestMethod.POST)
	public @ResponseBody
	String update(User user, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(StringConstants.LOGIN_USER);

		loginUser.setStrPhone(user.getStrPhone());
		loginUser.setStrEmail(user.getStrEmail());

		userService.update(loginUser);

		AjaxObject ajaxObject = new AjaxObject("详细信息修改成功！");
		ajaxObject.setCallbackType("closeCurrent");
		return ajaxObject.toString();
	}
}
